package com.alibaba.citrus.ots.platform.enhance.facade.service;

import java.util.List;

import javax.annotation.Resource;

import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.platform.enhance.repository.CompanyRepository;
import com.alibaba.citrus.ots.platform.enhance.repository.RegionRepository;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcots.model.dto.RegionSDO;
import com.epoch.app.otsplatformenhance.api.companyquery.service.CompanyQueryService;
import com.epoch.app.otsplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.otsplatformenhance.dto.request.QueryCompanyRequest;
import com.epoch.app.otsplatformenhance.sdo.CompanySDO;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2021/9/3 12:26
 */
@Primary
@Service
public class CompanyQueryServiceImpl implements CompanyQueryService {

    @Resource
    CompanyRepository companyRepository;

    @Resource
    RegionRepository regionRepository;

    @Override
    @FacadeInvoker
    public Result<CompanySDO> getCompany(IdQueryRequest request) {
        return Result.success(companyRepository.getCompany(request.getId()));
    }

    @Override
    @FacadeInvoker
    public Result<List<CompanySDO>> pageQueryCompanyList(QueryCompanyRequest request) {
        PageResult<List<CompanySDO>> pageResult = companyRepository.pageQueryCompanyList(request);
        pageResult.getContent().forEach(sdo -> {
            if(sdo.getRegistrationProvinceCode() != null) {
                List<RegionSDO> regionList = regionRepository.batchQueryRegionByCodes(Lists.newArrayList(sdo.getRegistrationProvinceCode(), sdo.getRegistrationCityCode(), sdo.getRegistrationAreaCode()));
                String[] registrationName = new String[3];
                regionList.forEach(region -> {
                    registrationName[region.getDivLevel() - 1] = region.getName();
                });

                StringBuffer registration = new StringBuffer();
                registration.append(registrationName[0]);
                if(registrationName[1] != null){
                    registration.append("/");
                    registration.append(registrationName[1]);
                }
                if(registrationName[2] != null){
                    registration.append("/");
                    registration.append(registrationName[2]);
                }
                sdo.setRegistration(registration.toString());
            }
        });
        return Result.listSuccess(pageResult.getContent(), pageResult.getTotal());
    }

}
